package com.github.service.impl;

import com.github.bean.User;
import com.github.mapper.UserMapper;
import com.github.mapper.UserStatusMapper;
import com.github.service.UserServer;
import com.github.util.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

@Service
public class UserServerImpl implements UserServer {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserStatusMapper userStatusMapper;

    @Override
    public boolean login(String account, String password) {
        User user = userMapper.findByAccount(account);
        boolean flag = user != null && user.getPassword().equals(password);
        if (flag) {
            userStatusMapper.updateServerStatus(account, 1);
        }
        return flag;
    }

    @Override
    public void logout(String account) {
        userStatusMapper.updateServerStatus(account, 0);
    }

    @Override
    public void addUser(String account) {
        String password = Utils.getRandomString(5);
        userMapper.addUser(account, password);
    }

    @Override
    public boolean addUser(String account, String password) {
        int flag = userMapper.addUser(account, password);
        return flag > 0;
    }

    @Override
    public boolean delUser(String account) {
        int flag = userMapper.delUser(account);
        return flag > 0;
    }

    @Override
    public boolean updatePassword(String account, String password) {
        int flag = userMapper.updatePassword(account, password);
        return flag > 0;
    }

    @Override
    public boolean reserveAccount(String account) {
        int flag = userMapper.reserveAccount(account);
        return flag > 0;
    }

    @Override
    public boolean unReserveAccount(String account) {
        int flag = userMapper.unReserveAccount(account);
        return flag > 0;
    }

    @Override
    public User getUser(String username) {
        return userMapper.findByAccount(username);
    }

    @Override
    public String getPassword(String account) {
        return userMapper.getPassword(account);
    }

    @Override
    public List<User> getReserveUser() {
        return userMapper.getReserveUser();
    }

    @Override
    public boolean isReserveAccount(String account) {
        User user = userMapper.findByAccount(account);
        if (user == null) {
            return false;
        }
        return userMapper.findByAccount(account).isReserve();
    }

    @Override
    public List<User> getAllUser() {
        return userMapper.getAllUser();
    }

    @Override
    public List<User> getAllNonReservedUser() {
        return userMapper.getAllNonReservedUser();
    }

    @Override
    public void delAllAccount() {
        userMapper.delAllAccount();
    }

    @Override
    public void delAllNonReservedAccount() {
        userMapper.delAllNonReservedAccount();
    }
}
